package com.vvvtimes.demo.util.endecrypt;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class BcDesUtil {

    private static final BouncyCastleProvider provider;

    //BouncyCastle与JDK加解密类区别
    //KeyFactory.getInstance("RSA"); +provider-->KeyFactory.getInstance("RSA", provider)
    //Cipher.getInstance("RSA");  +provider-->Cipher.getInstance("RSA", provider)
    //Signature.getInstance("SHA1withRSA"); +provider-->Signature.getInstance("SHA1withRSA", provider);
    //KeyGenerator.getInstance("DES") ; +provider-->KeyGenerator.getInstance("DES", provider); 或者KeyGenerator.getInstance("DES","BC")

    /**
     * 偏移变量，固定占8位字节
     */
    private final static String IV_PARAMETER = "12345678";

    /*
     * 生成key
     */
    public byte[] generateKey() {
        KeyGenerator keyGenerator = null;
        try {
            keyGenerator = KeyGenerator.getInstance("DES",provider);
            keyGenerator.init(56);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] encoded = secretKey.getEncoded();
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 生成key
     *
     * @param password 密钥字符串
     * @return 密钥对象
     * @throws Exception
     */
    private static Key convertKey(byte[] password) throws Exception {
        DESKeySpec dks = new DESKeySpec(password);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES",provider);
        return keyFactory.generateSecret(dks);
    }

    /**
     * DES加密
     */
    public static byte[] encrypt(byte[] data, byte[] password) {
        if (password == null || password.length < 8) {
            throw new RuntimeException("加密失败，key不能小于8位");
        }
        if (data == null)
            return null;
        try {
            Key secretKey = convertKey(password);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding",provider);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes("utf-8"));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte[] bytes = cipher.doFinal(data);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * DES解密解密字符串
     */
    public static byte[] decrypt(byte[] data, byte[] password) {
        if (password == null || password.length < 8) {
            throw new RuntimeException("加密失败，key不能小于8位");
        }
        if (data == null)
            return null;
        try {
            Key secretKey = convertKey(password);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding",provider);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes("utf-8"));
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            byte[] bytes = cipher.doFinal(data);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * byte数组转十六进制
     *
     * @param bytes
     * @return
     */
    public static String byte2HexString(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        if (bytes != null) {
            for (Byte b : bytes) {
                hex.append(String.format("%02X", b.intValue() & 0xFF));
            }
        }
        return hex.toString();
    }

    //测试
    public static void main(String[] args) throws Exception {
        String source = "admin测试信息1234!@#$%^&*()_+";
        System.out.println("原  文: " + source);
        String password = "lw112190@2023";
        byte[] encryptDataBytes = encrypt(source.getBytes("utf-8"), password.getBytes("utf-8"));
        String encryptData = byte2HexString(encryptDataBytes);
        System.out.println("加密后: " + encryptData);
        byte[] decryptDataBytes = decrypt(encryptDataBytes, password.getBytes("utf-8"));
        String decryptData = new String(decryptDataBytes, "utf-8");
        ;
        System.out.println("解密后: " + decryptData);
    }

    static {
        provider = new BouncyCastleProvider();
    }
}
